using RealtimeCollabGame.Application.Commands;
using RealtimeCollabGame.Application.Interfaces;
using RealtimeCollabGame.Domain.Entities;

namespace RealtimeCollabGame.Application.Handlers;

public class LeaveGameCommandHandler
{
    private readonly IGameRepository _gameRepository;
    private readonly IPlayerRepository _playerRepository;

    public LeaveGameCommandHandler(IGameRepository gameRepository, IPlayerRepository playerRepository)
    {
        _gameRepository = gameRepository;
        _playerRepository = playerRepository;
    }

    public async Task<Game> HandleAsync(LeaveGameCommand command)
    {
        var game = await _gameRepository.GetByCodeAsync(command.GameCode);
        if (game == null)
        {
            throw new InvalidOperationException($"房间代码 {command.GameCode} 不存在");
        }

        // 查找玩家
        var player = game.Players.FirstOrDefault(p => p.NickName == command.PlayerNickName);
        if (player == null)
        {
            throw new InvalidOperationException("玩家不在房间中");
        }

        // 从游戏中移除玩家
        game.RemovePlayer(player.Id);
        await _gameRepository.UpdateAsync(game);

        return game;
    }
} 